#pragma once

#include "ThreadPool.hpp"
#include "tcp_server.hpp"
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <string.h>
#include <string>
#include <map>
//执行处理逻辑
void HandlerHelper(int sock)
{
    cout<<"进行回调处理: debug sock: "<<sock<<endl;
    //回显消息
    while(true)
    {
        char buffer[1024]={0};
        //接收客户端的消息
        ssize_t s=read(sock,buffer,sizeof(buffer)-1);
        if(s>0)
        {
            buffer[s]=0;
            cout<<"client# "<<buffer<<endl;
            string message=buffer;
            if(message=="quit")
            {
                write(sock,"quit success!",strlen("quit success!"));
                break;
            }
            message+="[server_echo]";
            write(sock,message.c_str(),message.size());
        }
        else if(s==0)
        {
            cout<<"client close..."<<endl;
            break;
        }
        else
        {
            cerr<<"read error"<<endl;
            break;
        }
    }
}

std::map<std::string,std::string> dict={
    {"apple","苹果"},
    {"banana","香蕉"},
    {"hello","你好"},
    {"张晓曼","儿子"}
};

void HandlerTranslation(int sock)
{
    cout<<"进行翻译处理: debug sock: "<<sock<<endl;
    //基于短连接
    char buffer[1024]={0};
    //接收客户端的消息
    ssize_t s=read(sock,buffer,sizeof(buffer)-1);
    if(s>0)
    {
        buffer[s]=0;
        cout<<"client# "<<buffer<<endl;
        string message=buffer;
        string res="不知道";
        if(dict.find(message)!=dict.end())
        {
            res=dict[message];
        }
        write(sock,res.c_str(),res.size());
    }
    else if(s==0)
    {
        cout<<"client close..."<<endl;
    }
    else
    {
        cerr<<"read error"<<endl;
    }
}
//单进程-单执行流-不推荐
void HandlerSock_V1(int sock)
{
    HandlerHelper(sock);
}

//多进程-稳定，但没有上限
void HandlerSock_V2(int sock)
{
    if(fork()==0)
    {
        //child-子进程
        if(fork()>0)
        {
            exit(0);//子进程终止
        }
        //孙子进程成为孤儿进程-被OS领养，孙子进程结束后，OS会进行孙子进程的回收
        HandlerHelper(sock);
        exit(0);
    }
    //等待回收子进程
    waitpid(-1,nullptr,0);
}
void* Routine(void* args)
{
    int sock=*(int*)args;
    delete (int*)args;
    //线程分离-不用进行等待
    pthread_detach(pthread_self());
    HandlerHelper(sock);
    close(sock);//线程自己进行关闭
    return nullptr;
}
//多线程-轻量化，健壮性不足
void HandlerSock_V3(int sock)
{
    pthread_t tid;
    int* p=new int(sock);
    pthread_create(&tid,nullptr,Routine,p);
}

class Task
{
public:
    Task(int _sock):sock(_sock){}
    Task(){}
    void operator()()
    {
        cout<<"当前处理线程："<<pthread_self()<<endl;
        HandlerTranslation(sock);
        close(sock);
    }
private:
    int sock;
};
//线程池-避免过多线程或者进程调度造成过多的消耗
void HandlerSock_V4(int sock)
{
    ThreadPool<Task>::GetInstance(5)->Put(Task(sock));
}
